<template>
  <div class="createPost-container">
    <div class="sticky-container">
      <el-button v-if="Number(type) === 1" v-loading="loading" type="primary" @click="updateUser">
        保存
      </el-button>
    </div>
    <div class="createPost-main-container">
      <div class="title-container">详情信息:</div>
      <div class="table-container">
        <div class="table-item">
          <div class="item-label">员工姓名</div>
          <el-input v-model="detail.name" />
        </div>
        <div class="table-item">
          <div class="item-label">联系方式</div>
          <el-input v-model="detail.tel" />
        </div>
        <div class="table-item">
          <div class="item-label">飞友UID</div>
          <el-input v-model="detail.uid" readonly disabled />
        </div>
      </div>
      <div class="title-container">
        人脸信息:
        <el-upload
          action=""
          :before-upload="beforeAvatarUpload"
          accept="image/jpeg,image/jpg,image/png"
          :show-file-list="false"
          :http-request="(event) => addFace(event, detail.id)"
        >
          <el-button
            size="small"
            type="primary"
            :disabled="(detail.faceList||[]).length >= 6"
          >
            点击上传
          </el-button>
        </el-upload>
      </div>
      <div class="img-container">
        <div
          v-for="item in detail.faceList || []"
          :key="item.id"
          style="position:relative"
          @mouseenter="hoverId = item.id"
          @mouseleave="hoverId = null"
        >
          <i
            v-if="hoverId === item.id"
            class="el-icon-error face-close"
            @click="onDelete(item.id)"
          />
          <el-avatar
            shape="square"
            :size="140"
            fit="cover"
            :src="getUrl(item.imagePath)"
          >
            <img src="@/assets/error.png">
          </el-avatar>
        </div>
      </div>
      <div class="title-container">打卡记录:</div>
      <List :data="detail.reportList" />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import List from './List'
import { getInfo, addFace, updateUser, deleteFace } from '@/api/member'

export default {
  name: 'MemberDetail',
  components: {
    List
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tempRoute: {},
      detail: {},
      loading: false,
      hoverId: null
    }
  },
  computed: {
    lang() {
      return this.$store.getters.language
    },
    ...mapGetters([
      'type'
    ])
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    onMouseenter() {
      console.log(111)
    },
    fetchData(id) {
      getInfo({ id })
        .then((response) => {
          this.detail = response.object || {}

          // set tagsview title
          this.setTagsViewTitle()

          // set page title
          this.setPageTitle()
        })
        .catch((err) => {
          console.log(err)
        })
    },
    setTagsViewTitle() {
      const title = this.lang === 'zh' ? '人员详情' : '人员详情'
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = '人员详情'
      document.title = `${title}`
    },
    updateUser() {
      const data = {
        userId: this.detail.id,
        name: this.detail.name,
        tel: this.detail.tel
      }
      if (this.loading) return
      this.loading = true
      updateUser(data).then(() => {
        this.loading = false
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    addFace({ file }, userId) {
      const faceList = this.detail.faceList || []
      if (faceList.length >= 6) {
        this.$message.error('最多上传6张人脸图片')
        return
      }
      const formData = new FormData()
      formData.append('files', file)
      formData.append('userId', userId)
      addFace(formData).then(() => {
        this.$notify({
          title: '成功',
          message: '上传成功',
          type: 'success',
          duration: 2000
        })
        const id = this.$route.params && this.$route.params.id
        this.fetchData(id)
      })
    },
    onDelete(id) {
      this.$confirm('确认删除吗？', '警告', {
        width: '240px',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: '警告'
      }).then(() => {
        const formData = new FormData()
        formData.append('faceId', id)
        deleteFace(formData).then(() => {
          this.detail.faceList = this.detail.faceList.filter(item => item.id !== id)
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    handleExceed(files) {
      this.$message.error(
        `当前限制选择 6 个文件，本次选择了 ${files.length} 个文件`
      )
    },
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/jpg', 'image/png'].includes(
        file.type
      )

      if (!isJPG) {
        this.$message.error('人脸图片只能是jpg、jpeg、png格式!')
        return false
      }
      if (file.size < 10 * 1024) {
        this.$message.error('人脸图片大小不能小于10KB!')
        return false
      }

      if (file.size > 512 * 1024) {
        this.$message.error('人脸图片大小不能大于512KB!')
        return false
      }
      return true
    },
    getUrl(url) {
      if (url) {
        if (url.startsWith('/9j')) {
          return `data:image/png;base64,${url}`
        } else {
          return url
        }
      }
      return null
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 12px 20px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }
  .sticky-container {
    padding: 10px 20px;
    text-align: right;
  }
  .table-container {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
  }

  .table-item {
    width: 200px;
  }

  .el-avatar {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .img-container {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
  }

  .item-label {
    color: #909399;
    margin-bottom: 5px;
    font-weight: 600;
  }

  .title-container {
    font-size: 20px;
    font-weight: 600;
    margin: 20px 0;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .face-container {
    height: 120px;
  }

  .face-close {
    position: absolute;
    top: -12px;
    right: -12px;
    color: #F56C6C;
    cursor: pointer;
    z-index: 10;
    font-size: 24px;
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}
</style>
